#include<iostream>
#include<vector>
#include<string>
using namespace std;



struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) 
         : val(x)
         , left(left)
         ,right(right) 
     {}
 };


string s;
string tree2str(TreeNode* root) {
    if (root == nullptr)
        return s;

    s += to_string(root->val);
    if (root->left || root->right) {
        s += "(";
        tree2str(root->left);
        s += ")";
    }

    if (root->right) {
        s += "(";
        tree2str(root->right);
        s += ")";
    }
    return s;
}
 

int main()
{
    TreeNode* n1 = new TreeNode(1);
    TreeNode* n2 = new TreeNode(2);
    TreeNode* n3 = new TreeNode(3);
    TreeNode* n4 = new TreeNode(4);

    n1->left = n2;
    n1->right = n3;
    n2->left = n4;

    cout << tree2str(n1) << endl;

    return 0;
}